//
//  HNSH_OrderDetailViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/3/1.
//

#import "HNSH_OrderDetailViewController.h"

//view
#import "HNSH_OrderDetailHeaderView.h"
#import "HNSH_OrderDetailBottomView.h"
#import "HNSH_OrderDetailCell.h"
#import "HNSH_ConfirmOrderGoodsCell.h"
#import "HNSH_OrderDetailHeader.h"

//vc
#import "HNSH_LogisticsViewController.h"                    //物流
#import "HNSH_CashierPayViewController.h"                   //收银台
#import "HNSH_ConfirmOrderViewController.h"                 //确认订单
#import "HNSH_RefundApplyViewController.h"                  //售后申请
#import "HNSH_RefundDetailViewController.h"                 //售后详情

@interface HNSH_OrderDetailViewController ()

/* headerView */
@property (nonatomic, strong) HNSH_OrderDetailHeaderView *headerView;
/* bottomView */
@property (nonatomic, strong) HNSH_OrderDetailBottomView *bottomView;

/* listAry */
@property (nonatomic, strong) NSArray *listAry;

/* detailModel */
@property (nonatomic, strong) HNSH_OrderDetailModel *detailModel;

@end

static NSString *HNSH_OrderDetailCellID = @"HNSH_OrderDetailCellID";
static NSString *HNSH_ConfirmOrderGoodsCellID = @"HNSH_ConfirmOrderGoodsCellID";
static NSString *HNSH_OrderDetailHeaderID = @"HNSH_OrderDetailHeaderID";

@implementation HNSH_OrderDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadOrderDetail];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self showNavTitle:@"订单详情" showLeftItem:YES];
    self.navView.backgroundColor = [UIColor clearColor];
    self.navView.titleLabel.textColor = [UIColor appWhiteLabelColor];
    [self.navView.leftButton setImage:[UIImage imageNamed:@"base_nav_back_white"] forState:UIControlStateNormal];
    
    [self configTableView];
    
    [self configBottomView];
}

//MARK: 点击按钮
- (void)clickBtnWithBtn:(UIButton *)sender{
    HNSH_OrderListModel * model = self.orderModel;
    if ([sender.currentTitle isEqualToString:@"确认收货"]) {
        //确认收货
        [self showViewWithText:@"是否确认收货？" model:model type:2];
    }
    if ([sender.currentTitle isEqualToString:@"取消订单"]) {
        //取消订单
        [self showViewWithText:@"是否取消该订单？" model:model type:3];
    }
    if ([sender.currentTitle isEqualToString:@"删除订单"]) {
        //删除订单
        [self showViewWithText:@"是否删除该订单？" model:model type:4];
    }
    if ([sender.currentTitle isEqualToString:@"再次购买"]) {
        //再次购买
        [self buyAgainWithModel:model];
    }
    if ([sender.currentTitle isEqualToString:@"查看物流"]) {
        //查看物流
        if (![model.shipping_code isNotBlank]) {
            [self.view makeToast:@"暂无物流信息，不能查看物流"];
            return;
        }
        HNSH_LogisticsViewController * vc = [HNSH_LogisticsViewController new];
        vc.orderModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([sender.currentTitle isEqualToString:@"立即付款"]) {
        //立即付款
        [self payWithModel:model];
    }
    if ([sender.currentTitle isEqualToString:@"申请售后"]) {
        HNSH_RefundApplyViewController * vc = [HNSH_RefundApplyViewController new];
        vc.orderId = model.uid;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([sender.currentTitle isEqualToString:@"售后详情"]) {
        HNSH_RefundDetailViewController * vc = [HNSH_RefundDetailViewController new];
        vc.orderId = model.uid;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

//MARK: 展示弹框
- (void)showViewWithText:(NSString *)text model:(HNSH_OrderListModel *)model type:(NSInteger)type{
    WeakSelf(weakSelf);
    [HNSH_AlertView showTitle:text des:@"" buttonTitle:@"确定" buttonColor:[UIColor appGreenColor] buttonClick:^{
        [weakSelf changeStatusWithModel:model type:type];
    }];
}

//MARK: 修改订单状态
- (void)changeStatusWithModel:(HNSH_OrderListModel *)model type:(NSInteger)type{
    if (type == 4) {
        //删除订单
        [self deleteOrderWithModel:model];
    } else if (type == 3) {
        //取消订单
        [self cancelOrderWithModel:model];
    } else if (type == 2) {
        //确认收货
        [self completeOrderWithModel:model];
    }
}

//MARK: 再次购买
- (void)buyAgainWithModel:(HNSH_OrderListModel *)model {
    HNSH_ConfirmOrderGoodsModel *specModel = model.items[0];
    HNSH_ConfirmOrderViewController * vc = [HNSH_ConfirmOrderViewController new];
    vc.goods_id = specModel.goods_id;
    vc.spec_id = specModel.spec_id;
    vc.quantity = [specModel.quantity integerValue];
    vc.payment_type = model.payment_type;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)pushVCWithModel:(HNSH_CashierPayModel *)model{
    HNSH_CashierPayViewController * vc = [HNSH_CashierPayViewController new];
    vc.payModel = model;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark netWorking
//MARK: 订单详情
- (void)loadOrderDetail {
    [HNSH_ShopNetServer requestGoodsOrderDetailWithOrderId:self.orderModel.uid success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSDictionary * data = responseObject.resultset;
            HNSH_OrderDetailModel * model = [HNSH_OrderDetailModel yy_modelWithDictionary:data];
            self.detailModel = model;
            
            self.headerView = nil;
            if (![model.shipping_code isNotBlank]) {
                self.headerView.frame = CGRectMake(0, 0, kScreenWidth, kNavBarAndStatusBarHeight+150);
            } else {
                self.headerView.frame = CGRectMake(0, 0, kScreenWidth, kNavBarAndStatusBarHeight+246);
            }
            self.tableView.tableHeaderView = self.headerView;
            self.headerView.model = model;
            
            self.bottomView.model = model;
            
            self.listAry = self.detailModel.expense_items;
            
            [self.tableView reloadData];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 删除订单
- (void)deleteOrderWithModel:(HNSH_OrderListModel *)model{
    [HNSH_ShopNetServer requestGoodsOrderRemoveWithOrderId:model.uid success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self loadOrderDetail];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 取消订单
- (void)cancelOrderWithModel:(HNSH_OrderListModel *)model{
    [HNSH_ShopNetServer requestGoodsOrderCancelWithOrderId:model.uid success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self loadOrderDetail];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 确认收货
- (void)completeOrderWithModel:(HNSH_OrderListModel *)model{
    [HNSH_ShopNetServer requestGoodsOrderCompleteWithOrderId:model.uid success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self loadOrderDetail];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}


//MARK: 立即付款
- (void)payWithModel:(HNSH_OrderListModel *)model{
    [HNSH_ShopNetServer requestGoodsOrderPaymentInfoWithOrderId:model.uid success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSDictionary * data = responseObject.resultset;
            HNSH_CashierPayModel * model = [HNSH_CashierPayModel yy_modelWithDictionary:data];
            [self pushVCWithModel:model];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

#pragma mark lazy
- (HNSH_OrderDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[HNSH_OrderDetailHeaderView alloc]init];
    }
    return _headerView;
}

- (HNSH_OrderDetailBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[HNSH_OrderDetailBottomView alloc]init];
        WeakSelf(weakSelf);
        _bottomView.clickBtnBlock = ^(UIButton * _Nonnull button) {
            [weakSelf clickBtnWithBtn:button];
        };
    }
    return _bottomView;
}

- (void)configBottomView {
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(55+kBottomSafeHeight);
    }];
}

//MARK: 配置tableView
- (void)configTableView {
//    [self setupRefresh:self.tableView option:ST_RefreshDefault];
//    [self setupEmpty:self.tableView image:[UIImage imageNamed:@""] title:@""];
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, kBottomSafeHeight+55, 0));
    }];
    [self.tableView registerClass:[HNSH_OrderDetailCell class] forCellReuseIdentifier:HNSH_OrderDetailCellID];
    [self.tableView registerClass:[HNSH_ConfirmOrderGoodsCell class] forCellReuseIdentifier:HNSH_ConfirmOrderGoodsCellID];
    [self.tableView registerClass:[HNSH_OrderDetailHeader class] forHeaderFooterViewReuseIdentifier:HNSH_OrderDetailHeaderID];
}

#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.detailModel.items.count;
    }
    return self.listAry.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 52.0f;
    }
    return 8.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        HNSH_OrderDetailHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HNSH_OrderDetailHeaderID];
        header.shopNameString = self.detailModel.shop_name;
        return header;
    }
    return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 106;
    }
    return 28;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        HNSH_ConfirmOrderGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_ConfirmOrderGoodsCellID];
        cell.model = self.detailModel.items[indexPath.row];
        return cell;
    }
    HNSH_OrderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_OrderDetailCellID];
    cell.model = self.listAry[indexPath.row];
    return cell;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
